<template>
  <div class="auth-container">
    <div class="auth-card">
      <h2 class="auth-title">登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="account">账号</label>
          <input
            type="text"
            id="account"
            v-model="account"
            required
            placeholder="请输入学号、邮箱或手机号"
          >
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="password"
            required
            placeholder="请输入密码"
          >
        </div>
        <button type="submit" class="auth-btn">登录</button>
        <div class="auth-switch">
          <span>还没有账号？</span>
          <router-link to="/register">立即注册</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { socketService } from '@/utils/socket-utils';
import { useRouter } from 'vue-router';
import axios from 'axios';
import moment from 'moment';

// 表单数据
const account = ref('');
const password = ref('');
const errorMsg = ref('');
const router = useRouter();

/**
 * 处理登录逻辑
 * 自动判断账号类型(学号/邮箱)并提交登录请求
 */
const handleLogin = async () => {
  try {
    errorMsg.value = '';
    // 终端日志输出登录请求参数
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [登录] 请求参数: ${JSON.stringify({ account: account.value, password: password.value })}`);
    const response = await axios.post('/api/auth/login', {
      account: account.value,
      password: password.value
    });

    // 存储token和用户信息
    localStorage.setItem('token', response.data.token);
    localStorage.setItem('user', JSON.stringify(response.data.user));
    // 终端日志输出登录响应结果
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [登录] 响应结果: ${JSON.stringify(response.data)}`);

    // 登录成功后建立WebSocket连接
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [登录] 开始建立WebSocket连接，用户ID: ${response.data.user.id}`);
    try {
      socketService.init(response.data.user.id);
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [登录] WebSocket连接初始化成功`);
      // 跳转到管理员主页或首页
      if (response.data.user.role === 1) {
        router.push('/admin');
      } else {
        router.push('/');
      }
    } catch (wsError) {
      console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [登录] WebSocket连接失败:`, wsError);
      console.error(`登录成功，但WebSocket连接失败: ${wsError instanceof Error ? wsError.message : String(wsError)}`);
      // 即使WebSocket连接失败，也允许用户登录
      if (response.data.user.role === 1) {
        router.push('/admin');
      } else {
        router.push('/');
      }
    }
    //window.location.reload();无用代码暂时保留
  } catch (err: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [登录] 登录失败:`, err, err?.response?.data);
    errorMsg.value = err.response?.data?.message || '登录失败，请检查账号密码';
  }
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

.auth-title {
  text-align: center;
  margin-bottom: 25px;
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #475569;
  font-weight: 500;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.2s ease;
}

input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.auth-btn {
  width: 100%;
  padding: 14px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.auth-btn:hover {
  background-color: #2563eb;
  transform: translateY(-2px);
}

.auth-switch {
  margin-top: 15px;
  text-align: center;
  color: #64748b;
}

.auth-switch a {
  color: #3b82f6;
  text-decoration: none;
  font-weight: 500;
}
</style>